<?php
// +----------------------------------------------------------------------
// | OpenAdmin [ 基于ThinkPHP6和Vue3后台管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2022 OpenAdmin All rights reserved.
// +----------------------------------------------------------------------
// | Licensed (https://gitee.com/open_admin/OpenAdmin/blob/master/LICENSE)
// +----------------------------------------------------------------------
// | 作者: About 
// +----------------------------------------------------------------------
// | 修改时间:2022/8/5-18:23
// +----------------------------------------------------------------------
namespace app\common\utils;

use think\facade\Cache;
use ip2region\Ip2Region;
use think\facade\Request;

class IpInfoUtils
{
    /**
     * 获取IP地址的详细信息
     * @param string $ip 要查询的IP地址,为空自动获取当前请求IP
     * @return array
     */
    public static function getInfo(string $ip = ''): array
    {
        if (empty($ip)) {
            $cdn = Request::header("X-Forwarded-For");//如果网站配置CDN加速,获取真实客户访问IP
            $ip  = empty($cdn) ? Request::ip() : explode(',', $cdn)[0];//CDN为空获取当前访问的IP,不为空则取第一个值
        }

        $cache_key = 'ip_info_' . $ip;
        $ip_info   = Cache::get($cache_key);

        if (empty($ip_info)) {
            try {
                $response = explode('|', Ip2Region::search($ip));
            } catch (\Exception) {
                $response = [];
            }

            $ip_info = [
                'ip'       => $ip,
                'country'  => '',
                'province' => '',
                'city'     => '',
                'region'   => '',
                'isp'      => '',
            ];

            if (!empty($response)) {
                $ip_info['country']  = $response[0] == 0 ? '' : $response[0];//国家
                $ip_info['province'] = $response[2] == 0 ? '' : $response[2];//省份
                $ip_info['city']     = $response[3] == 0 ? '' : $response[3];//城市
                $ip_info['region']   = $response[1] == 0 ? '' : $response[1];//区/县
                $ip_info['isp']      = $response[4] == 0 ? '' : $response[4];//运营商

                Cache::set($cache_key, $ip_info, 0);
            }
        }

        return $ip_info;
    }
}